package com.yrk.servlet;

import com.yrk.dao.FileDao;
import com.yrk.entity.FileUp;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;

@WebServlet("/fileServlet")
@MultipartConfig
public class FileInsertServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        FileDao fileDao = (FileDao) ac.getBean("fileDao");
        Part filePart = request.getPart("file");
        String contentDisposition = filePart.getHeader("content-disposition");
        String fileName = null;
        if (contentDisposition != null) {
            for (String cd : contentDisposition.split(";")) {
                if (cd.trim().startsWith("filename")) {
                    fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                    break;
                }
            }
        }

        //定义存储上传时文件夹路径（相对于项目根目录）
        String uploadDirPath=getServletContext().getRealPath("/")+"uploadedImages";
        File uploadDir = new File(uploadDirPath);
        if (!uploadDir.exists()) {
            //如果文件夹不存在，则创建
            uploadDir.mkdirs();
        }
        //生成存储文件的路径
        String filePath = uploadDirPath + File.separator + fileName;
        try(InputStream fileContent = request.getInputStream();
            FileOutputStream fos = new FileOutputStream(new File(filePath))){
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fileContent.read(buffer)) !=-1) {
                fos.write(buffer, 0, length);
            }
        }
        //构建相对路径以存储到数据库中
        String relativeFilePath = "uploadedImages" + File.separator + fileName;
        //将文件路径存储到数据库
        FileUp fileUp = new FileUp();
        fileUp.setFilename(fileName);
        fileUp.setFilepath(relativeFilePath);
        int num = fileDao.insertFile(fileUp);
        PrintWriter out = response.getWriter();
        if (num > 0) {
            out.print("true");
        }else{
            out.print("false");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
